package com.swpu.filter;

import cn.hutool.captcha.generator.MathGenerator;
import cn.hutool.extra.spring.SpringUtil;
import com.swpu.common.CacheConstants;
import com.swpu.component.RedisUtils;
import com.swpu.result.ResultCode;
import com.swpu.utils.ResponseUtils;
import jakarta.annotation.Resource;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
/**
 * 验证码校验过滤器
 * @author 宋建博
 * @date 2024/1/10
 */
@Component
public class VerifyCodeFilter extends OncePerRequestFilter {

    public static final String CAPTCHA_CODE_PARAM_NAME = "captchaCode";
    public static final String CAPTCHA_KEY_PARAM_NAME = "captchaKey";

    @Resource
    private RedisUtils redisUtils;

    @Override
    public void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
        // 检验登录接口的验证码
        boolean isLoginUrl = request.getRequestURI().contains("/login");
        if (isLoginUrl) {
            // 请求中的验证码
            String verifyCode = request.getParameter(CAPTCHA_CODE_PARAM_NAME);
            // 缓存中的验证码
            String verifyCodeKey = request.getParameter(CAPTCHA_KEY_PARAM_NAME);
            String cacheVerifyCode= (String)redisUtils.get(CacheConstants.CAPTCHA_CODE_PREFIX + verifyCodeKey);
            if (cacheVerifyCode == null) {
                ResponseUtils.writeErrMsg(response, ResultCode.VERIFY_CODE_TIMEOUT);
            } else {
                // 验证码比对
//                MathGenerator mathGenerator = new MathGenerator();
                if (cacheVerifyCode.equalsIgnoreCase(verifyCode)) {
                    chain.doFilter(request, response);
                } else {
                    ResponseUtils.writeErrMsg(response, ResultCode.VERIFY_CODE_ERROR);
                }
            }
        } else {
            // 非登录接口放行
            chain.doFilter(request, response);
        }
    }

}
